package com.beta.service.impl;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.beta.service.IMenusService;
import com.beta.dto.admin.MenuDto;
import com.beta.entity.Menus;
import com.beta.mapper.MenusMapper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Menus 表数据服务层接口实现类
 */
@Service
public class MenusService extends SuperServiceImpl<MenusMapper, Menus> implements IMenusService {

    @Override
    public List<MenuDto> getAdminMenus(Integer adminId) {
        if (Objects.isNull(adminId)) {
            return Collections.emptyList();
        }

        List<MenuDto> menus = baseMapper.getMenusByAdminId(adminId);
        return flatToHierachical(menus);
    }

    private List<MenuDto> flatToHierachical(List<MenuDto> menus) {
        if (CollectionUtils.isEmpty(menus)) {
            return Collections.emptyList();
        }

        Map<Integer, MenuDto> menusMap = menus.stream()
                .collect(Collectors.toMap(MenuDto::getId, Function.identity()));
        Iterator<MenuDto> iterator = menus.iterator();
        while (iterator.hasNext()) {
            MenuDto menu = iterator.next();
            MenuDto parentMenu = menusMap.get(menu.getParentId());
            if (Objects.nonNull(parentMenu)) {
                iterator.remove();
                List<MenuDto> children = parentMenu.getChildren();
                if (Objects.isNull(children)) {
                    children = new ArrayList<>();
                    parentMenu.setChildren(children);
                }
                children.add(menu);
            }
        }
        return menus;
    }

    @Override
    public Map<String, String> getAdminMenuActionsMap(Integer adminId) {
        if (Objects.isNull(adminId)) {
            return Collections.emptyMap();
        }

        List<MenuDto> adminMenus = baseMapper.getMenusByAdminId(adminId);
        if (CollectionUtils.isEmpty(adminMenus)) {
            return Collections.emptyMap();
        }

        Map<String, String> menuActionsMap = adminMenus.stream()
                .filter(menu -> StringUtils.isNotBlank(menu.getPath()))
                .collect(Collectors.toMap(MenuDto::getPath, MenuDto::getActions));
        return menuActionsMap;
    }
}